package com.jueming.miser.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jueming.miser.auth.feign.UserFeignService;
import com.jueming.miser.auth.to.MiserUserTo;
import com.jueming.miser.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("auth/miserauth")
public class LoginController {
    @Autowired
    UserFeignService userFeignService;

    @RequestMapping("/register")
    public R register(@RequestBody MiserUserTo to) {
        //调用user微服务进行注册
        return userFeignService.register(to);
//        if (register.getCode() == 0) {
//            //成功则直接进行登录
//            return "redirect:/login.html";
//        } else {
//            //失败
//            return "redirect:/reg.html";
//        }
    }

    @RequestMapping("/login")
    public R login(@RequestBody MiserUserTo to, HttpSession session) {
        //调用user远程服务进行登录校验
        R login = userFeignService.login(to);
        if (login.getCode() != 0) {
            //登陆失败
            return login;
        } else {
            //登录成功
            String data = JSONObject.toJSONString(login.getData("data", new TypeReference<MiserUserTo>() {}));
            session.setAttribute("loginUser", data);

            return R.error("error");
        }
    }

    @RequestMapping("/getloginUser")
    public R getloginUser(HttpSession session) {
        //获取用户信息
        Object to = session.getAttribute("loginUser");
        if (to == null) {
            return R.error("获取用户信息失败");
        } else {
            return R.ok("获取用户信息成功").setData(to);
        }
    }

    @RequestMapping("/loginout")
    public R loginOut(HttpSession session) {
        session.removeAttribute("loginUser");
        return R.ok("登出成功");
    }
}
